/* eslint-disable no-param-reassign */
import orgApi from '@/api/modules/system/org'
// 处理组织结构数据，为不同导次加不同的图标
function handleTreeData (data) {
  data.forEach(item => {
    if (typeof item.parentId === 'undefined') {
      item.slots = {
        icon: 'firm'
      }
    } else if (item.childOrganizations.length > 0) {
      item.slots = {
        icon: 'bumen1'
      }
    } else {
      item.slots = {
        icon: 'bumen'
      }
    }
    item.childOrganizations.length && handleTreeData(item.childOrganizations)
  })
}
const state = {
  treeData: [],
  // 当前被选中的组织
  selectedOrg: null
}
const mutations = {
  SET_TREE_DATA: (state, val) => {
    state.treeData = val
  },
  SET_SELECTED_ORG: (state, val) => {
    state.selectedOrg = val
  }
}
const actions = {
  getTreeData ({ commit, state }) {
    return new Promise((resolve, reject) => {
      orgApi.getOrgAllData().then(res => {
        handleTreeData(res.data)
        if (!state.selectedOrg) {
          const firstOrg = res.data && res.data[0]
          if (firstOrg) {
            // eslint-disable-next-line max-len
            commit('SET_SELECTED_ORG', { id: firstOrg.id, name: firstOrg.name, parentId: firstOrg.parentId ? firstOrg.parentId : null })
          }
        }
        commit('SET_TREE_DATA', res.data)
        resolve(true)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // eslint-disable-next-line no-unused-vars
  addOrgData ({ commit, dispatch }, data) {
    return new Promise((resolve, reject) => {
      orgApi.addOrg(data).then(res => {
        resolve(res.data)
        dispatch('getTreeData')
      }).catch(err => {
        reject(err)
      })
    })
  },
  // eslint-disable-next-line no-unused-vars
  editOrgData ({ commit, dispatch }, data) {
    return new Promise((resolve, reject) => {
      orgApi.editOrg(data).then(res => {
        resolve(res.data)
        dispatch('getTreeData')
      }).catch(err => {
        reject(err)
      })
    })
  }
}
export default {
  state,
  mutations,
  actions
}
